package com.security.springsecurity02.web;

import com.security.springsecurity02.entity.UserInfo;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/user")
@RestController
public class UserInfoControler {

    //只能新增id < 4的用户
    @RequestMapping("/add")
    @PreAuthorize("#id < 4")
    public UserInfo add(int id){
        UserInfo info = new UserInfo();
        info.setId(id);
        info.setName("user" + id);
        return info;
    }
    // @PostAuthorize对结果进行校验，如果返回的数据id是2的倍数则成功返回，否则无权限
    @PostAuthorize("returnObject.id % 2 == 0")
    @RequestMapping("/get")
    public UserInfo get(int id){
        UserInfo info = new UserInfo();
        info.setId(id);
        info.setName("user" + id);
        return info;
    }
    // @PostFilter对结果集中id是2的倍数进行过滤
    @RequestMapping("/query")
    @PostFilter("filterObject.id % 2 == 0")
    public List<UserInfo> query(){
        List<UserInfo> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            UserInfo info = new UserInfo();
            info.setId(i);
            info.setName("user" + i);
            list.add(info);
        }
        return list;
    }
    //Filter target must be a collection, array, map or stream type, but was 4
    @RequestMapping("/delete")
    @PreFilter(filterTarget = "id",value = "id % 2 ==0")
    public String delete(String id){
        return "删除用户id="+id;
    }
}
